﻿using System;
using System.Xml;

namespace digiTwitter.ExtensionMethods
{
    public static class XmlNodeExtensions
    {
        public static string GetString(this XmlNode input, string nodeName)
        {
            if(input.SelectSingleNode(nodeName) != null)
                return input.SelectSingleNode(nodeName).InnerText;

            throw new XmlException(string.Format("The node {0} was not found.",nodeName));
        }

        public static int GetInt(this XmlNode input, string nodeName)
        {
            int result;

            if (input.SelectSingleNode(nodeName) != null)
                if (int.TryParse(input.SelectSingleNode(nodeName).InnerText, out result))
                    return result;
                else
                    throw new System.InvalidCastException(string.Format("Could not convert node {0} to Integer.",nodeName));

            throw new XmlException(string.Format("The node {0} was not found.", nodeName));
        }

        public static bool GetBool(this XmlNode input, string nodeName)
        {
            bool result;

            if (input.SelectSingleNode(nodeName) != null)
                if (bool.TryParse((input.SelectSingleNode(nodeName).InnerText), out result))
                    return result;
                else
                    throw new System.InvalidCastException(string.Format("Could not convert node {0} to Boolean.", nodeName));

            throw new XmlException(string.Format("The node {0} was not found.", nodeName));
        }

        public static DateTime GetDateTime(this XmlNode input, string nodeName)
        {
            DateTime result;

            if (input.SelectSingleNode(nodeName) != null)
                if (DateTime.TryParse(input.SelectSingleNode(nodeName).InnerText, out result))
                    return result;
                else
                    throw new System.InvalidCastException(string.Format("Could not convert node {0} to DateTime.", nodeName));

            throw new XmlException(string.Format("The node {0} was not found.", nodeName));
        }
    }
}
